﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using LayeredSkin.Controls;
using LayeredSkin.DirectUI;
using Dandan.Menu;
using QQ.Controls;
using Dandan.Properties;
using System.Drawing.Drawing2D;
using Newtonsoft.Json;
using System.Drawing.Printing;
using Dandan.Tool;

namespace Dandan
{
    public partial class FromMain : LayeredBaseForm
    {
        #region 变量

        private ScanerHook listener = new ScanerHook();

        /// <summary>
        /// 全局DuiBaseControl控件申明（重复利用）
        /// </summary>
        private DuiBaseControl _baseControl;

        /// <summary>
        /// 选中的好友项ID(为选中为-1)
        /// </summary>
        public int ItemsIndex = -1;

        /// <summary>
        /// 选中的好友项ID(为选中为-1)
        /// </summary>
        public int GroupItemsIndex = -1;

        private Font _font = new Font("微软雅黑", 9.3F, FontStyle.Regular, GraphicsUnit.Point,
            ((byte)(134)));
        /// <summary>
        /// 是否已读取完列表
        /// </summary>
        public bool IsLoadedItems = false;

        //public static List<FrmChat> FrmChatsList = new List<FrmChat>();

        public FrmMainMenu QFrmMainMenu = null;
        //public FrmSetting QFrmSetting = null;
        #endregion

        #region 构造函数

        public FromMain()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
            layeredDragBar1.ForeColor =
                layeredDragBar2.ForeColor =
                    layeredDragBar3.ForeColor = layeredDragBar4.ForeColor = Color.FromArgb(255, Color.White);

            LoadUserInfo();

            listener.ScanerEvent += Listener_ScanerEvent;
        }

        #endregion


        private void Listener_ScanerEvent(ScanerHook.ScanerCodes codes)
        {
            MessageBox.Show(codes.Result);
        }

        #region 方法

        void LoadUserInfo()
        {
            if (UserData.GetData().data.avatar != null && UserData.GetData().data.avatar != "")
            {
                HeadImg.LoadAsync(UserData.GetData().data.avatar);
            }
            if (UserData.GetData().data.nickname != null)
            {
                UserName.Text = UserData.GetData().data.nickname;
            }
        }

        /// <summary>
        /// 加载底部菜单按钮及工具栏
        /// </summary>
        public void LoadButtonToolAndMenu()
        {
            #region 初始化第一行16*16工具栏

            Bitmap[] btmBitmaps16 = new Bitmap[6]
            {
                Resources.weiyun, Resources.webqq_16, Resources.chongwu, Resources.music, Resources.qqgame_16,
                Resources.chong
            };
            /*for (int i = 0; i < btmBitmaps16.Length; i++)
            {
                AddBottontoolItems16(btmBitmaps16[i], i, 0);
            }*/

            #endregion

            #region 初始化第二行24*24菜单及工具栏

            Bitmap[] btmBitmaps24 = new Bitmap[5]
            {
                Resources.MainMenuShine_01, Resources.tools_hover, Resources.message_highlight,
                Resources.filemanager_hover,
                Resources.myCollection_mainpanel_hover
            };
            for (int i = 0; i < btmBitmaps24.Length; i++)
            {
                AddBottontoolItems24(btmBitmaps24[i], i, 1);
            }

            #region 加载菜单查找按钮

            _baseControl = DuiBaseControlClass.AddDuiBaseControl(null, ImageLayout.None, Cursors.Default,
                new Size(65, 28), new Point(24 * btmBitmaps24.Length + 15, 24 + 5));

            DuiLabel img = DuiBaseControlClass.AddDuiLabel("", _font, new Size(24, 24), new Point(4, 4));
            img.BackgroundImage = Resources.find_hover;
            img.BackgroundImageLayout = ImageLayout.Center;
            //    new Size(24, 24), new Point(4, 4), false);
            //_baseControl.Controls.Add(img);
            //添加查找文字
            DuiLabel searchlb = DuiBaseControlClass.AddDuiLabel("查找", _font, new Size(45, 20), new Point(28, 5));
            _baseControl.Controls.Add(img);
            _baseControl.Controls.Add(searchlb);
            BottonBaseControl.DUIControls.Add(_baseControl);

            #endregion

            #endregion
        }

        /// <summary>
        /// 初始化好友列表
        /// </summary>
        public void CreatList()
        {
            #region 添加好友列表

            //WebQq.FriendsList = WebQq.FriendsList.OrderByDescending(vip => vip.Isvip).ThenByDescending(flag => flag.IsOnline).ToList();
            //for (int g = 0; g < WebQq.GetCategories.Count; g++)
            //{
            //    DuiLabel group = ChatListBox.AddChatGroup(WebQq.GetCategories[g].Name, "close",
            //        WebQq.GetFriendsCountFormCategories(WebQq.GetCategories[g].Index), 0);
            //    ChatListBox.Items.Add(group);
            //    ChatListBox.RefreshList();
            //    Application.DoEvents();
            //    for (int i = 0; i < WebQq.FriendsList.Count; i++)
            //    {
            //        if (WebQq.FriendsList[i].Categoriesid == WebQq.GetCategories[g].Index)
            //        {
            //            TagFrirendInfo tagFrirendInfo = ChatListBox.GetObj(Resources._1_100, WebQq.FriendsList[i]);

            //            DuiBaseControl item = ChatListBox.AddChatItems(tagFrirendInfo);
            //            WebQq.FriendsList[i].ChartListIndex = int.Parse(item.Name);
            //            item.Tag = tagFrirendInfo;
            //            ChatListBox.Items.Add(item);
            //            ChatListBox.RefreshList();
            //        }
            //    }
            //}
            //for (int i = 0; i < 5; i++)
            //{
                DuiLabel group = ChatListBox.AddChatGroup(string.Format("订单"), "close",
                    orderData.data.Length, 0);
                ChatListBox.Items.Add(group);
                ChatListBox.Items.Add(group);
                ChatListBox.RefreshList();
                Application.DoEvents();
                for (int j = 0; j < orderData.data.Length; j++)
                {
                    TagFrirendInfo tagFrirendInfo = ChatListBox.GetObj(orderData.data[j]);

                    DuiBaseControl item = ChatListBox.AddChatItems(tagFrirendInfo);
                    item.Tag = tagFrirendInfo;
                    ChatListBox.Items.Add(item);
                    ChatListBox.RefreshList();
                    Application.DoEvents();
                }
            //}
            #endregion

            IsLoadedItems = true;
            ChatListBox.RefreshList();
        }

        public void CreatProjectList()
        {
            #region 添加好友列表
            
            DuiLabel group = ChatListBox2.AddChatGroup(string.Format("商品列表"), "close",
                m_ModelsData.data.Length, 0);
            ChatListBox2.Items.Add(group);
            ChatListBox2.Items.Add(group);
            ChatListBox2.RefreshList();
            Application.DoEvents();
            for (int j = 0; j < m_ModelsData.data.Length; j++)
            {
                TagFrirendInfo tagFrirendInfo = ChatListBox2.GetObj(m_ModelsData.data[j]);

                DuiBaseControl item = ChatListBox2.AddChatItems(tagFrirendInfo);
                item.Tag = tagFrirendInfo;
                ChatListBox2.Items.Add(item);
                ChatListBox2.RefreshList();
                Application.DoEvents();
            }
            //}
            #endregion

            IsLoadedItems = true;
            ChatListBox2.RefreshList();
        }

        /// <summary>
        /// 添加底部Tool按钮（大小16*16）
        /// </summary>
        /// <param name="btmBitmap">tool图标</param>
        /// <param name="index">从左到右第几项</param>
        /// <param name="heightindex">高度行号下标</param>
        public void AddBottontoolItems16(Bitmap btmBitmap, int index, int heightindex)
        {
            DuiBaseControl BottontoolItems = new DuiBaseControl();
            BottontoolItems.Size = new System.Drawing.Size(24, 24);
            BottontoolItems.Location = new Point(24 * index + 5, heightindex * 30 + 5);
            //vip.BackColor = Color.Transparent;
            BottontoolItems.BackgroundImage = btmBitmap;
            BottontoolItems.Tag = index;
            BottontoolItems.BackgroundImageLayout = ImageLayout.Center;
            BottontoolItems.MouseClick += Tools16MouseClick;
            BottontoolItems.MouseEnter += HightMouseEnter;
            BottontoolItems.MouseLeave += HightMouseLeave;
            BottonBaseControl.DUIControls.Add(BottontoolItems);
        }

        /// <summary>
        /// 添加底部菜单Tool按钮（大小24*24）
        /// </summary>
        /// <param name="btmBitmap">菜单tool图标</param>
        /// <param name="index">从左到右第几项</param>
        /// <param name="heightindex">高度行号下标</param>
        public void AddBottontoolItems24(Bitmap btmBitmap, int index, int heightindex)
        {
            DuiBaseControl BottontoolItems = new DuiBaseControl();
            BottontoolItems.Size = new System.Drawing.Size(28, 28);
            if (index == 0)
                BottontoolItems.Location = new Point(24 * index + 5, heightindex * 24 + 5);
            else
            {
                BottontoolItems.Location = new Point(24 * index + 10, heightindex * 24 + 5);
            }
            //vip.BackColor = Color.Transparent;
            BottontoolItems.BackgroundImage = btmBitmap;
            BottontoolItems.BackgroundImageLayout = ImageLayout.Center;
            BottontoolItems.Tag = index;
            BottontoolItems.MouseClick += Tools24MouseClick;
            BottontoolItems.MouseEnter += HightMouseEnter;
            BottontoolItems.MouseLeave += HightMouseLeave;
            BottonBaseControl.DUIControls.Add(BottontoolItems);
        }

        public DuiBaseControl BandEven(DuiBaseControl dbct)
        {
            dbct.MouseEnter += HightMouseEnter;
            dbct.MouseLeave += HightMouseLeave;
            return dbct;
        }

        /*public static FrmChat FindFrmChat(string qq)
        {
            FrmChat fc = null;
            for (int i = 0; i < FrmChatsList.Count; i++)
            {
                if (!FrmChatsList[i].IsDisposed)
                {
                    if (FrmChatsList[i].QtagFrirendInfo.QQ == qq)
                    {
                        fc = FrmChatsList[i];
                        break;
                    }
                }
            }
            return fc;
        }*/

        #endregion

        #region 事件

        #region 窗体初始化加载事件

        /// <summary>
        /// 窗体加载事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmMain_Load(object sender, EventArgs e)
        {
            Image image = this.HeadImg.Image;
            Image newImage = CutEllipse(image, new Rectangle(0, 0, 60, 60), HeadImg.Size);
            this.HeadImg.Image = newImage;

            //HeadImg.LoadAsync("http://b.hiphotos.baidu.com/image/pic/item/96dda144ad345982b391b10900f431adcbef8415.jpg");
            Hide();
            timer1.Enabled = true;
            notifyIcon1.Text = string.Format("QQ:{0}({1})", "BinGoo", "315567586");
            //设置启动特效
            this.Animation.Effect = new LayeredSkin.Animations.RandomCurtainEffect();
            //初始化tab背景图片
            layeredTabControl1.BackgroundImage = Resources.tabbg;
            layeredTabControl1.BackgroundImageLayout = ImageLayout.Tile;
            //初始化搜索框样式
            TxtSearch.BackColor = BtnSearch.BackColor = Color.Gainsboro;
            //初始化底部工具栏透明样式
            BottonBaseControl.BackColor = Color.FromArgb(90, Color.White);
 
            //获取头像
            Bitmap headBitmap = Resources.勾引;

            //List<GroupInfo> gi = WebQq.GetGroups();
            //加载头部个人信息
            //LoadHeadInfo(headBitmap, "BinGoo", 0, 64, true, "没有拆不散的情侣，只有不努力的小三... ...", 5, 99, Resources.Big_2);
            //加载底部工具栏
            LoadButtonToolAndMenu();

            
            GetOrderData();
            GetModelsData();

            int i;
            string pkInstalledPrinters;
            using (PrintDocument pd = new PrintDocument())
            {
                for (i = 0; i < PrinterSettings.InstalledPrinters.Count; i++)  //开始遍历  
                {
                    pkInstalledPrinters = PrinterSettings.InstalledPrinters[i];  //取得名称  
                    PrintList.Add(pkInstalledPrinters);
                    ToolStripItem ts_1 = new ToolStripMenuItem(pkInstalledPrinters);
                    ts_1.Tag = i;
                    ts_1.Click += new EventHandler(ts_1_Click);
                    ((ToolStripDropDownItem)(contextMenuStrip1.Items[0])).DropDownItems.Add(ts_1);
                    if (pd.PrinterSettings.IsDefaultPrinter)                     //判断是否为默认打印机  
                    {
                        //string OldActPrn = pd.PrinterSettings.PrinterName;              //保存名称，后面要用  
                        //cmbPrinterList.Text = pd.PrinterSettings.PrinterName;    //显示默认打印机名称  
                    }
                }
            }

            listener.Start();

            //AddCommodityInfo addCommodityInfo = new AddCommodityInfo();
            //addCommodityInfo.Show();
        }

        List<string> PrintList = new List<string>();

        /*添加的"正常"子菜单Click事件*/
        private void ts_1_Click(object sender, EventArgs e)
        {
            ToolStripItem button = sender as ToolStripItem;

            PrintModel pmTitle = new PrintModel();
            pmTitle.FontFamily = "宋体";
            pmTitle.FontSize = Convert.ToInt32(16);
            pmTitle.IsBold = true;
            pmTitle.Text = new System.IO.StringReader("\n" + "益民停车场管理系统");//首行需要空行,某些打印机首行不为空时会出现“首行乱码问题”

            PrintModel pmContent1 = new PrintModel();
            pmContent1.FontFamily = "宋体";
            pmContent1.FontSize = Convert.ToInt32(12);
            pmContent1.IsBold = false;
            pmContent1.Text = new System.IO.StringReader("*****************************************");

            PrintModel pmContent2 = new PrintModel();
            pmContent2.FontFamily = "宋体";
            pmContent2.FontSize = Convert.ToInt32(9);
            pmContent2.IsBold = false;

            StringBuilder sb = new StringBuilder();
            //sb.Append("\n");
            //sb.Append("\t益民停车场管理系统\n");
            //sb.Append("*****************************************\n");
            sb.Append("进场时间：" + DateTime.Now.ToString() + "\n");
            sb.Append("出场时间：" + DateTime.Now.AddHours(2).ToString() + "\n");
            sb.Append("停车时长：2小时\n");
            sb.Append("停车收费：5元\n");

            pmContent2.Text = new System.IO.StringReader(sb.ToString());

            PrintModel[] pms = new PrintModel[] { pmTitle, pmContent1, pmContent2 };

            TicketPrinterHelper.Print(pms, "", PrintList[Convert.ToInt32(button.Tag)]);
        }

        OrderData orderData;
        public void GetOrderData()
        {
            string loginUrl = "/api/v1/orders";
            
            string json = HttpWebResponseUtility.MakeRequestGet(loginUrl);
            try
            {
                orderData = JsonConvert.DeserializeObject<OrderData>(json);
                //OrderData.SetData(orderData);
                this.BeginInvoke((MethodInvoker)delegate ()
                {
                    //清除好友列表
                    ChatListBox.Items.Clear();
                    //加载好友与群列表
                    CreatList();

                    //notifyIcon1.Icon = Resources.ggimonline;
                    notifyIcon1.Text = string.Format("QQ:{0}({1})\r\n声音：开启\r\n消息提示框：关闭\r\n会话消息：任务栏头像不闪动", "BinGoo",
                       "315567586");
                    Show();
                    IsLoadedItems = true;
                });
            }
            catch (Exception)
            {
                MessageBox.Show("系统提示" + json);
            }
        }

        ModelsData m_ModelsData;
        public void GetModelsData()
        {
            string loginUrl = "/api/v1/projects?shop_id=1&per_page=10&page=1";

            string json = HttpWebResponseUtility.MakeRequestGet(loginUrl);
            try
            {
                m_ModelsData = JsonConvert.DeserializeObject<ModelsData>(json);
                //OrderData.SetData(orderData);
                this.BeginInvoke((MethodInvoker)delegate ()
                {
                    //清除好友列表
                    ChatListBox2.Items.Clear();
                    //加载好友与群列表
                    CreatProjectList();

                    //notifyIcon1.Icon = Resources.ggimonline;
                    notifyIcon1.Text = string.Format("QQ:{0}({1})\r\n声音：开启\r\n消息提示框：关闭\r\n会话消息：任务栏头像不闪动", "BinGoo",
                       "315567586");
                    Show();
                    IsLoadedItems = true;
                });
            }
            catch (Exception)
            {
                MessageBox.Show("系统提示" + json);
            }
        }

        private Image CutEllipse(Image img, Rectangle rec, Size size)
        {
            Bitmap bitmap = new Bitmap(size.Width, size.Height);
            using (Graphics g = Graphics.FromImage(bitmap))
            {
                using (TextureBrush br = new TextureBrush(img, System.Drawing.Drawing2D.WrapMode.Clamp, rec))
                {
                    br.ScaleTransform(bitmap.Width / (float)rec.Width, bitmap.Height / (float)rec.Height);
                    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                    g.FillEllipse(br, new Rectangle(Point.Empty, size));
                }
            }
            return bitmap;
        }

        #endregion

        #region 最小化和退出程序按钮事件

        /// <summary>
        /// 关闭按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnCloseClick(object sender, EventArgs e)
        {

            this.Animation.Effect = new LayeredSkin.Animations.GradualCurtainEffect();
            this.Animation.Asc = true;
            Animation.Interval = 1;
            //等动画结束后关闭程序
            Thread t = new Thread(new ThreadStart(CloseSystem));
            t.Start();

            Close();
        }

        //延迟一秒等待完成动画效果后关闭系统方法
        public void CloseSystem()
        {
            Thread.Sleep(1000);
            System.Environment.Exit(0);
        }

        /// <summary>
        /// 最小化按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnMiniClick(object sender, EventArgs e)
        {
            //this.WindowState = FormWindowState.Minimized;
            this.Hide();
        }

        #endregion

        #region 选项卡选择改变事件

        /// <summary>
        /// TabControl选项切换时触发的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TabControlSelectedIndexChanged(object sender, EventArgs e)
        {
            switch (layeredTabControl1.SelectedIndex)
            {
                case 0:
                    tabPage1.ImageIndex = 3;
                    tabPage2.ImageIndex = 6;
                    break;
                case 1:
                    tabPage1.ImageIndex = 5;
                    tabPage2.ImageIndex = 6;
                    break;
                case 2:
                    tabPage1.ImageIndex = 3;
                    tabPage2.ImageIndex = 8;
                    break;
            }
        }

        #endregion

        #region 我的头像单击事件

        /// <summary>
        /// 点击头像事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void headimg_Click(object sender, EventArgs e)
        {

        }
        private void headimgMouseEnter(object sender, EventArgs e)
        {
            //窗体的TopLeft值
            int UserTop = ((DuiBaseControl) sender).LocationToScreen.Y;
            int UserLeft = this.Left - 279;
            //屏幕不包括任务栏的高度
            int PH = Screen.GetWorkingArea(this).Height;
            //判断是否超过屏幕高度
            if (UserTop + 181 > PH)
            {
                UserTop = PH - 181 - 5;
            }
            //判断是否小于屏幕左边
            if (UserLeft < 0)
            {
                UserLeft = this.Right + 5;
            }
            //窗体不为空传值
            /*if (_frmUserInfo != null)
            {
                if (_frmUserInfo.IsDisposed)
                {
                    _frmUserInfo = new FrmUserinfo(new Point(UserLeft, UserTop));
                }
                    
            }
            else
            {
                    _frmUserInfo = new FrmUserinfo(new Point(UserLeft, UserTop));
            }
            
            _frmUserInfo.Location = _frmUserInfo.LoactionPoint = new Point(UserLeft, UserTop);
            _frmUserInfo.LoactionPoint = new Point(UserLeft, UserTop);
            _frmUserInfo.ToolsControl.Visible = true;
            //_frmUserInfo.RefleshChatData("315567586", "BinGoo", "没有拆不散的情侣，只有不努力的小三... ...");
            _frmUserInfo.MyInfo("BinGoo", "没有拆不散的情侣，只有不努力的小三... ...");
            _frmUserInfo.Height = 260;
            _frmUserInfo.IsClose = false;
            _frmUserInfo.Show();*/
        }
        private void headimgMouseLeave(object sender, EventArgs e)
        {
            /*if (_frmUserInfo == null)
            {
                return;
            }
            if (!_frmUserInfo.IsDisposed)
            {
                ThreadPool.QueueUserWorkItem(new WaitCallback(l =>
                {
                    while (!_frmUserInfo.IsDisposed)
                    {
                        Thread.Sleep(300);
                        if (!_frmUserInfo.Bounds.Contains(Cursor.Position))
                        {

                            _frmUserInfo.IsClose = true;

                            _frmUserInfo.Close();
                        }
                    }
                }));
            }*/
        }
        #endregion

        #region 查找文本框事件

        /// <summary>
        /// 搜索框文本改变时触发的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TxtSearch_TextChanged(object sender, EventArgs e)
        {
            if (TxtSearch.Text != "")
            {
                TxtSearch.BackColor = BtnSearch.BackColor = Color.White;
            }
            else
            {
                TxtSearch.BackColor = BtnSearch.BackColor = Color.Gainsboro;
            }
        }

        /// <summary>
        /// 查找按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnSearch_Click(object sender, EventArgs e)
        {
            ChatListBox.IsSmallHead = !ChatListBox.IsSmallHead;
            ChatListBox.FreshItems();
        }

        #endregion

        #region 悬浮天气窗体事件

        //private FrmWeather frmWeather;

        private void WeatherMouseEnter(object sender, EventArgs e)
        {
            //窗体的TopLeft值
            int UserTop = this.Top;
            //int UserLeft = this.Left - 240 - 2;
            int UserLeft = this.Right;
            //屏幕不包括任务栏的高度
            int PH = Screen.GetWorkingArea(this).Height;
            //判断是否超过屏幕高度
            if (UserTop + 250 > PH)
            {
                UserTop = PH - 250 - 2;
            }

            int PW = Screen.GetWorkingArea(this).Width;
            //判断是否大于屏幕右边
            if (UserLeft + 240 + 2 > PW)
            {
                UserLeft = this.Left - 240 - 2;
            }
            //窗体不为空传值
            /*if (frmWeather != null)
            {
                if (frmWeather.IsDisposed)
                    frmWeather = new FrmWeather(new Point(UserLeft, UserTop));
            }
            else
            {
                frmWeather = new FrmWeather(new Point(UserLeft, UserTop));

            }
            frmWeather.Location = new Point(UserLeft, UserTop);
            frmWeather.LoactionPoint = new Point(UserLeft, UserTop);
            frmWeather.IsOpen = true;
            frmWeather.TimShow(true);*/
        }

        private void WeatherMouseLeave(object sender, EventArgs e)
        {
            /*if (frmWeather == null)
            {
                return;
            }
            frmWeather.IsOpen = false;*/
            //if (frmWeather.Visible)
            //{
            //    frmWeather.Hide();
            //}
        }

        #endregion

        #region 状态按钮及状态items单击改变事件

        /// <summary>
        /// 状态按钮点击事件（弹出状态菜单选项）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StateMenuMouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Left)
            {
                DuiBaseControl send = (DuiBaseControl)sender;
                this.contextMenuStrip1.Show(new Point(send.LocationToScreen.X, send.LocationToScreen.Y + send.Height));

            }
        }

        private void StateItemsClick(object sender, EventArgs e)
        {
            string state = ((ToolStripMenuItem)sender).Tag.ToString();
            switch (state)
            {
                case "0x0A":
                    Setstateimg("在线");
                    break;
                case "0x14":
                    Setstateimg("隐身");
                    break;
                case "0x1E":
                    Setstateimg("离开");
                    break;
                case "0x32":
                    Setstateimg("忙碌");
                    break;
                case "0x3C":
                    Setstateimg("q我吧");
                    break;
                case "0x46":
                    Setstateimg("请勿打扰");
                    break;
                case "0x28":
                    Setstateimg(" 离线");
                    break;
            }
            //HeadBaseControl.DUIControls[2].BackgroundImage = ((ToolStripMenuItem) sender).Image;
        }

        /// <summary>
        /// 更改状态图片
        /// </summary>
        /// <param name="state"></param>
        public void Setstateimg(string state)
        {

        }

        #endregion

        #region 任务栏图标相关事件

        //private FrmMsglist _frmMsglist;

        private void notifyIcon1_MouseMove(object sender, MouseEventArgs e)
        {
            int left = (Cursor.Position.X / 20 * 20) - 297 / 2;

            //窗体不为空传值
            //if (_frmMsglist != null)
            //{
            //    if (_frmMsglist.ChatList.Items.Count < 1)
            //    {
            //        notifyIcon1.Text = string.Format("QQ:{0}({1})\r\n声音：开启\r\n消息提示框：关闭\r\n会话消息：任务栏头像不闪动",
            //            WebQq.user.QQNick, WebQq.GetTrueUin(WebQq.user.QQID.ToString(), "1"));
            //        //this.notifyIcon1.ShowBalloonTip(30, "提醒", "监控程序正在运行", ToolTipIcon.Info);
            //    }
            //    else
            //    {
            //        notifyIcon1.Text = "";
            //        _frmMsglist.Left = left;
            //        _frmMsglist.timShowShow();
            //    }
            //}
            //else
            //{
            //    _frmMsglist = new FrmMsglist(this.WebQq);
            //    _frmMsglist.Left = left;
            //    _frmMsglist.timShowShow();
            //}
        }

        /// <summary>
        /// 鼠标左键单击任务栏图标显示窗体，右键显示菜单栏
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                this.Show();
            }
        }

        #endregion

        #region 好友列表项相关事件

        //private FrmUserinfo _frmUserInfo;

        /// <summary>
        /// 鼠标移动到头像时触发事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /*private void ChatListBoxMouseEnterHead(object sender, ChatListEventArgs e)
        {
            //窗体的TopLeft值
            int UserTop = e.HeadBaseControl.LocationToScreen.Y;
            int UserLeft = this.Left - 279;
            //屏幕不包括任务栏的高度
            int PH = Screen.GetWorkingArea(this).Height;
            //判断是否超过屏幕高度
            if (UserTop + 181 > PH)
            {
                UserTop = PH - 181 - 5;
            }
            //判断是否小于屏幕左边
            if (UserLeft < 0)
            {
                UserLeft = this.Right + 5;
            }

            TagFrirendInfo tag = (TagFrirendInfo)e.SelectItem.Tag;
            //窗体不为空传值
            if (_frmUserInfo != null)
            {
                if (_frmUserInfo.IsDisposed)
                {
                    _frmUserInfo = new FrmUserinfo(new Point(UserLeft, UserTop));
                }
                if (e.SelectItem.Tag != null)
                {
                    _frmUserInfo.Location = _frmUserInfo.LoactionPoint = new Point(UserLeft, UserTop);
                    _frmUserInfo.LoactionPoint = new Point(UserLeft, UserTop);
                    _frmUserInfo.ToolsControl.Visible = true;
                    _frmUserInfo.RefleshChatData(tag.Uin, tag.NicName, tag.Sign);
                    _frmUserInfo.Height = 260;
                    _frmUserInfo.IsClose = false;
                    _frmUserInfo.Show();
                }
            }
            else
            {
                if (e.SelectItem.Tag != null)
                {
                    _frmUserInfo = new FrmUserinfo(new Point(UserLeft, UserTop));
                    _frmUserInfo.Location = new Point(UserLeft, UserTop);
                    _frmUserInfo.LoactionPoint = new Point(UserLeft, UserTop);
                    _frmUserInfo.ToolsControl.Visible = true;
                    _frmUserInfo.RefleshChatData(tag.Uin, tag.NicName, tag.Sign);
                    _frmUserInfo.Height = 260;
                    _frmUserInfo.IsClose = false;
                    _frmUserInfo.Show();
                }
            }
        }*/

        ///// <summary>
        ///// 鼠标离开头像控件时不显示边框
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="e"></param>
        /*private void ChatListBoxMouseLeaveHead(object sender, ChatListEventArgs e)
        {
            if (_frmUserInfo == null)
            {
                return;
            }
            if (!_frmUserInfo.IsDisposed)
            {
                ThreadPool.QueueUserWorkItem(new WaitCallback(l =>
                {
                    while (!_frmUserInfo.IsDisposed)
                    {
                        Thread.Sleep(300);
                        if (!_frmUserInfo.Bounds.Contains(Cursor.Position))
                        {

                            _frmUserInfo.IsClose = true;

                            _frmUserInfo.Close();
                        }
                    }
                }));
            }
        }*/

        /// <summary>
        /// 双击好友列表事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <param name="es"></param>
        private void ChatListBoxDoubleClickItem(object sender, ChatListClickEventArgs e, MouseEventArgs es)
        {
            TagFrirendInfo tag = e.Friendinformation;
            //MessageBox.Show(string.Format("QQ:{0}\r\nVip:{1}\r\nVip等级{2}\r\n在线情况：{3}\r\nUIN{4}", tag.QQ, tag.IsVip,
            //    tag.VipLv, tag.FlagStatus, tag.Uin));
            /*FrmChat fc = FindFrmChat(tag.QQ);
            if (fc == null)
            {
                fc = new FrmChat(tag);
            }
            FrmChatsList.Add(fc);
            fc.Show();*/

        }


        
        #endregion

        #region 群列表项相关事件

        /// <summary>
        /// 鼠标移动到头像时触发事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /*private void GroupListBoxMouseEnterHead(object sender, ChatListEventArgs e)
        {
            ////窗体的TopLeft值
            //int UserTop = e.HeadBaseControl.LocationToScreen.Y;
            //int UserLeft = this.Left - 279;
            ////屏幕不包括任务栏的高度
            //int PH = Screen.GetWorkingArea(this).Height;
            ////判断是否超过屏幕高度
            //if (UserTop + 181 > PH)
            //{
            //    UserTop = PH - 181 - 5;
            //}
            ////判断是否小于屏幕左边
            //if (UserLeft < 0)
            //{
            //    UserLeft = this.Right + 5;
            //}

            //TagFrirendInfo tag = (TagFrirendInfo)e.SelectItem.Tag;
            ////窗体不为空传值
            //if (_frmUserInfo != null)
            //{
            //    if (e.SelectItem.Tag != null)
            //    {
            //        _frmUserInfo.Location = _frmUserInfo.LoactionPoint = new Point(UserLeft, UserTop);
            //        _frmUserInfo.LoactionPoint = new Point(UserLeft, UserTop);
            //        _frmUserInfo.ToolsControl.Visible = false;
            //        _frmUserInfo.RefleshChatData(tag.Uin, tag.NicName, tag.Sign);
            //        _frmUserInfo.Height = 200;
            //        _frmUserInfo.Show();
            //    }
            //}
            //else
            //{
            //    if (e.SelectItem.Tag != null)
            //    {
            //        _frmUserInfo = new FrmUserInfo(WebQq, new Point(UserLeft, UserTop));
            //        _frmUserInfo.Location = new Point(UserLeft, UserTop);
            //        _frmUserInfo.LoactionPoint = new Point(UserLeft, UserTop);
            //        _frmUserInfo.ToolsControl.Visible = false;
            //        _frmUserInfo.RefleshChatData(tag.Uin, tag.NicName, tag.Sign);
            //        _frmUserInfo.Height = 200;
            //        _frmUserInfo.Show();
            //    }
            //}
        }*/

        /// <summary>
        /// 鼠标离开头像控件时不显示边框
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /*private void GroupListBoxMouseLeaveHead(object sender, ChatListEventArgs e)
        {
            //if (_frmUserInfo == null)
            //{
            //    return;
            //}
            //if (_frmUserInfo.Visible)
            //{
            //    _frmUserInfo.Hide();
            //}
        }*/

        /// <summary>
        /// 双击好友列表事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <param name="es"></param>
        /*private void GroupListBoxDoubleClickItem(object sender, ChatListClickEventArgs e, MouseEventArgs es)
        {
            //TagFrirendInfo tag = e.Friendinformation;
            //MessageBox.Show(string.Format("群号:{0}\r\nVip:{1}\r\nVip等级{2}\r\n在线情况：{3}\r\nUIN{4}", tag.QQ, tag.IsVip,
            //    tag.VipLv, tag.FlagStatus, tag.Uin));
            //FrmChat fc = FindFrmChat(tag.Uin, "2");
            //if (fc == null)
            //{
            //    if (tag.QQ == "")
            //        tag.QQ = WebQq.GetTrueUin(tag.Uin, "2");
            //    e.SelectChatItem.Tag = tag;
            //    fc = new FrmChat(this.WebQq, tag, "2");
            //}
            //FrmChatsList.Add(fc);
            //fc.Show();
        }*/

        #endregion

        #region 登陆图标闪动
        Icon[] Loginicons =
            {
                Resources.Loading_1, Resources.Loading_2, Resources.Loading_3,
                Resources.Loading_4, Resources.Loading_5, Resources.Loading_6
            };
        int IcoIndex = 0;
        private void ShowIconTimerTick(object sender, EventArgs e)
        {
            if (!IsLoadedItems)
            {
                notifyIcon1.Icon = Loginicons[IcoIndex];
                IcoIndex++;
                if (IcoIndex == 6)
                    IcoIndex = 0;
            }
            timer1.Enabled = false;
        }
        #endregion

        #region 工具栏单击事件

        private void Tools16MouseClick(object sender, EventArgs e)
        {
            int index =(int) ((DuiBaseControl) sender).Tag;
            string name = "";
            switch (index)
            {
                case 0:
                    name = "微云";
                    break;
                case 1:
                    name = "WebQQ";
                    break;
                case 2:
                    name = "宠物";
                    break;
                case 3:
                    name = "QQ音乐";
                    break;
                case 4:
                    name = "QQ游戏";
                    break;
                case 5:
                    name = "QQ充值";
                    break;
            }
            MessageBox.Show(string.Format("点击了:{0}", name));
        }
        private void Tools24MouseClick(object sender, EventArgs e)
        {

            int index = (int)((DuiBaseControl)sender).Tag;
            if (index == 0)
            {
                #region 弹出菜单栏
                int left = ((DuiBaseControl) sender).LocationToScreen.X;
                int top = ((DuiBaseControl) sender).LocationToScreen.Y;
                //窗体的TopLeft值
                int UserTop = top;
                //int UserLeft = this.Left - 240 - 2;
                int UserLeft = left;
                //屏幕不包括任务栏的高度
                int PH = Screen.GetWorkingArea(this).Height;
                //判断是否超过屏幕高度
                if (UserTop < 0)
                {
                    UserTop = 0;
                }

                int PW = Screen.GetWorkingArea(this).Width;
                //判断是否大于屏幕右边
                if (UserLeft + 260 > PW)
                {
                    UserLeft = PW - 160;
                }
                //窗体不为空传值
                if (QFrmMainMenu != null)
                {
                    QFrmMainMenu.Location = new Point(left - 5, UserTop - 343);
                }
                else
                {
                    QFrmMainMenu = new FrmMainMenu();
                    QFrmMainMenu.Location = new Point(left - 5, UserTop - 343);
                }
                QFrmMainMenu.Show();
                #endregion
            } 
            else if (index == 1)
            {
                #region 设置窗体

                /*if (QFrmSetting == null)
                {
                    QFrmSetting=new FrmSetting();
                }
                else
                {
                    if (QFrmSetting.IsDisposed)
                    {
                        QFrmSetting=new FrmSetting();
                    }
                }
                QFrmSetting.Show();*/

                #endregion
            }
        }
        #endregion

        #region DuiBaseControl高亮显示和隐藏事件
        /// <summary>
        /// 鼠标离开控件时不显示边框
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void HightMouseLeave(object sender, EventArgs e)
        {
            ((DuiBaseControl)sender).Borders.TopColor =
                ((DuiBaseControl)sender).Borders.BottomColor =
                    ((DuiBaseControl)sender).Borders.LeftColor =
                        ((DuiBaseControl)sender).Borders.RightColor = Color.Transparent;
        }
        /// <summary>
        ///  鼠标进入控件时高亮显示边框
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void HightMouseEnter(object sender, EventArgs e)
        {

            ((DuiBaseControl)sender).Borders.TopColor =
                ((DuiBaseControl)sender).Borders.BottomColor =
                    ((DuiBaseControl)sender).Borders.LeftColor =
                        ((DuiBaseControl)sender).Borders.RightColor = Color.FromArgb(40, Color.Black);
        }
        #endregion

        #endregion

        private void PrintToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void FromMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            listener.Stop();
        }
    }
}
